package cn.geminis.crypto.tsp;

import cn.geminis.crypto.core.util.EncodeUtils;
import cn.geminis.crypto.csp.AbstractDigest;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.tsp.TimeStampReq;
import org.bouncycastle.tsp.TimeStampRequestGenerator;

import java.io.IOException;

/**
 * @author Allen
 */
public class TimeStampRequest {

    private org.bouncycastle.tsp.TimeStampRequest bcRequest;

    public org.bouncycastle.tsp.TimeStampRequest getBcRequest() {
        return bcRequest;
    }

    public TimeStampRequest() {
    }

    public TimeStampRequest(byte[] data) {
        TimeStampReq req = TimeStampReq.getInstance(EncodeUtils.fromDERorPEM(data));
        this.bcRequest = new org.bouncycastle.tsp.TimeStampRequest(req);
    }

    public byte[] getEncode() {
        try {
            return bcRequest.getEncoded();
        } catch (IOException e) {
            throw new RuntimeException("时间戳请求DER格式编码错误", e);
        }
    }

    public void generate(AbstractDigest digest, byte[] data) {

        byte[] digestData = digest.digest(data);

        TimeStampRequestGenerator generator = new TimeStampRequestGenerator();
        bcRequest = generator.generate(
                new ASN1ObjectIdentifier(digest.getAlgorithmOid()),
                digestData);
    }

}
